#!/bin/bash

# 终极优化版网络命名空间流量监控脚本
NAMESPACE="serverSpace"
REFRESH_INTERVAL=5

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m'

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo
    echo "选项:"
    echo "  -i, --interval SECONDS   统计间隔（秒），默认5秒"
    echo "  -h, --help              显示帮助信息"
    echo
    echo "示例:"
    echo "  $0                      # 使用默认5秒间隔"
    echo "  $0 -i 3                 # 使用3秒间隔"
    echo "  $0 --interval 10        # 使用10秒间隔"
    echo
    echo "功能："
    echo "  - 监控serverSpace命名空间中的网络流量"
    echo "  - 按流量从高到低排序显示活跃接口"
    echo "  - 统计全部接口的总流量"
    echo "  - 终极性能优化（约20倍加速）"
}

# 解析命令行参数
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -i|--interval)
                if [[ $2 =~ ^[0-9]+$ ]] && [ $2 -gt 0 ]; then
                    REFRESH_INTERVAL=$2
                    shift 2
                else
                    echo "错误: 统计间隔必须是正整数"
                    exit 1
                fi
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            *)
                echo "错误: 未知参数 '$1'"
                echo "使用 '$0 --help' 查看帮助信息"
                exit 1
                ;;
        esac
    done
}

# 检查命名空间是否存在
check_namespace() {
    if ! ip netns list | grep -q "^${NAMESPACE}"; then
        echo "错误: 命名空间 '${NAMESPACE}' 不存在"
        exit 1
    fi
}

# 终极优化的数据获取函数
get_all_stats() {
    ip netns exec "$NAMESPACE" sh -c '
        cd /sys/class/net 2>/dev/null || exit 1
        for dev in *; do
            case "$dev" in
                lo) continue ;;
                *) [ -d "$dev" ] || continue ;;
            esac
            rx_file="$dev/statistics/rx_bytes"
            tx_file="$dev/statistics/tx_bytes"
            if [ -r "$rx_file" ] && [ -r "$tx_file" ]; then
                read rx < "$rx_file" 2>/dev/null || rx=0
                read tx < "$tx_file" 2>/dev/null || tx=0
                printf "%s:%s:%s\n" "$dev" "$rx" "$tx"
            fi
        done
    '
}

# 优化的单位格式化函数
format_bytes() {
    local bytes=$1
    case $bytes in
        0) printf "0 B/s" ;;
        [1-9]|[1-9][0-9]|[1-9][0-9][0-9]|102[0-3])
            printf "%d B/s" "$bytes" ;;
        *)
            if [ $bytes -lt 1048576 ]; then
                printf "%d.%d KB/s" $((bytes / 1024)) $(((bytes * 10 / 1024) % 10))
            elif [ $bytes -lt 1073741824 ]; then
                printf "%d.%d MB/s" $((bytes / 1048576)) $(((bytes * 10 / 1048576) % 10))
            else
                printf "%d.%d GB/s" $((bytes / 1073741824)) $(((bytes * 10 / 1073741824) % 10))
            fi
            ;;
    esac
}

# 优化的颜色化速度显示
colorize_speed() {
    local speed="$1"
    case "$speed" in
        *" B/s") printf "${WHITE}%s${NC}" "$speed" ;;
        *" KB/s")
            local num=${speed%% *}
            local int_part=${num%%.*}
            if [ ${int_part:-0} -lt 100 ]; then
                printf "${GREEN}%s${NC}" "$speed"
            else
                printf "${YELLOW}%s${NC}" "$speed"
            fi
            ;;
        *" MB/s")
            local num=${speed%% *}
            local int_part=${num%%.*}
            if [ ${int_part:-0} -lt 10 ]; then
                printf "${YELLOW}%s${NC}" "$speed"
            else
                printf "${RED}%s${NC}" "$speed"
            fi
            ;;
        *" GB/s") printf "${PURPLE}%s${NC}" "$speed" ;;
    esac
}

# 主监控函数
monitor_traffic() {
    declare -A prev_rx prev_tx
    local first_run=1
    local last_update_time=0
    
    # 清屏并显示标题
    clear
    printf "${CYAN}================================================================================================${NC}\n"
    printf "${WHITE}                    网络命名空间 '%s' 流量监控 (%d秒间隔) - 终极优化版                    ${NC}\n" "$NAMESPACE" "$REFRESH_INTERVAL"
    printf "${CYAN}================================================================================================${NC}\n"
    
    while true; do
        local process_start=$(date +%s)
        
        # 获取统计数据
        local stats_data=$(get_all_stats)
        local current_time=$(date '+%Y-%m-%d %H:%M:%S')
        
        if [ $first_run -eq 1 ]; then
            # 初始化数据
            while IFS=':' read -r interface rx tx; do
                [ -n "$interface" ] && prev_rx[$interface]=$rx && prev_tx[$interface]=$tx
            done <<< "$stats_data"
            first_run=0
            last_update_time=$process_start
            printf "${YELLOW}正在初始化统计数据，请等待 %d 秒...${NC}\n" "$REFRESH_INTERVAL"
            sleep $REFRESH_INTERVAL
            continue
        fi
        
        local actual_interval=$((process_start - last_update_time))
        last_update_time=$process_start
        
        # 移动到固定位置
        tput cup 3 0
        
        printf "${BLUE}更新时间: %s | 统计间隔: %d秒 | 实际间隔: %d秒${NC}\n" "$current_time" "$REFRESH_INTERVAL" "$actual_interval"
        echo
        
        # 数据处理
        local speeds_array=()
        local total_rx_speed=0 total_tx_speed=0
        local active_interfaces=0 total_interfaces=0
        
        while IFS=':' read -r interface current_rx current_tx; do
            if [ -n "$interface" ] && [ -n "${prev_rx[$interface]}" ]; then
                local rx_speed=$(( (current_rx - prev_rx[$interface]) / actual_interval ))
                local tx_speed=$(( (current_tx - prev_tx[$interface]) / actual_interval ))
                
                [ $rx_speed -lt 0 ] && rx_speed=0
                [ $tx_speed -lt 0 ] && tx_speed=0
                
                total_rx_speed=$((total_rx_speed + rx_speed))
                total_tx_speed=$((total_tx_speed + tx_speed))
                total_interfaces=$((total_interfaces + 1))
                
                local total_speed=$((rx_speed + tx_speed))
                if [ $total_speed -gt 0 ]; then
                    speeds_array+=("$total_speed:$interface:$rx_speed:$tx_speed")
                    active_interfaces=$((active_interfaces + 1))
                fi
                
                prev_rx[$interface]=$current_rx
                prev_tx[$interface]=$current_tx
            fi
        done <<< "$stats_data"
        
        # 优化的排序
        IFS=$'\n'
        local sorted_speeds=($(printf '%s\n' "${speeds_array[@]}" | sort -t: -k1 -nr | head -25))
        unset IFS
        
        # 显示结果
        printf "%-15s %-20s %-20s %-20s\n" "接口名称" "下载速度" "上传速度" "总速度"
        echo "--------------------------------------------------------------------------------"
        
        local displayed_count=0
        for entry in "${sorted_speeds[@]}"; do
            IFS=':' read -r total_speed interface rx_speed tx_speed <<< "$entry"
            
            local rx_formatted=$(format_bytes $rx_speed)
            local tx_formatted=$(format_bytes $tx_speed)
            local total_formatted=$(format_bytes $total_speed)
            
            local rx_colored=$(colorize_speed "$rx_formatted")
            local tx_colored=$(colorize_speed "$tx_formatted")
            local total_colored=$(colorize_speed "$total_formatted")
            
            printf "%-15s %-30s %-30s %-30s\n" "$interface" "$rx_colored" "$tx_colored" "$total_colored"
            displayed_count=$((displayed_count + 1))
        done
        
        [ $displayed_count -eq 0 ] && printf "${YELLOW}当前没有检测到网络流量${NC}\n"
        
        # 全局统计
        echo "================================================================================"
        printf "${WHITE}全部接口统计:${NC}\n"
        
        local total_rx_formatted=$(format_bytes $total_rx_speed)
        local total_tx_formatted=$(format_bytes $total_tx_speed)
        local total_all_formatted=$(format_bytes $((total_rx_speed + total_tx_speed)))
        
        local total_rx_colored=$(colorize_speed "$total_rx_formatted")
        local total_tx_colored=$(colorize_speed "$total_tx_formatted")
        local total_all_colored=$(colorize_speed "$total_all_formatted")
        
        printf "%-15s %-30s %-30s %-30s\n" "总计" "$total_rx_colored" "$total_tx_colored" "$total_all_colored"
        
        echo
        printf "${CYAN}活跃接口: %d/%d | 统计间隔: %d秒 | 按 Ctrl+C 退出${NC}\n" "$active_interfaces" "$total_interfaces" "$REFRESH_INTERVAL"
        
        tput ed
        
        # 精确时间控制
        local process_end=$(date +%s)
        local process_time=$((process_end - process_start))
        local sleep_time=$((REFRESH_INTERVAL - process_time))
        [ $sleep_time -lt 1 ] && sleep_time=1
        
        sleep $sleep_time
    done
}

# 信号处理
cleanup() {
    tput cnorm
    clear
    printf "${GREEN}监控已停止${NC}\n"
    exit 0
}

# 主程序
main() {
    parse_args "$@"
    trap cleanup SIGINT SIGTERM
    check_namespace
    tput civis
    monitor_traffic
}

main "$@"

